package com.gitee.huanminabc.db_freedom.wrapper;


import com.gitee.huanminabc.db_freedom.base.SqlHelper;

import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * 如果不想使用mybatis-plus的mapper,可以使用这个类
 */
public class SqlWrapperHelper {
    private final SqlHelper sqlHelper;


    public SqlWrapperHelper(SqlHelper sqlHelper) {
        this.sqlHelper = sqlHelper;
    }

    public <T> T queryOne(LambdaSQL<T> sqlWrapper) {
        Class<T> entityClass = (Class<T>) sqlWrapper.getTableInfo().getEntityClass();
        return sqlHelper.queryOne(sqlWrapper,sqlWrapper.SQL().toSqlStructure(), entityClass, sqlWrapper.SQL().getParams().toArray());
    }

    public<T> List<T> queryList(LambdaSQL<T> sqlWrapper, Class<T> cl) {
        return sqlHelper.queryList(sqlWrapper,sqlWrapper.SQL().toSqlStructure(), cl, sqlWrapper.SQL().getParams().toArray());
    }
    public <T> List<Map<String, Object>> queryMaps(LambdaSQL<T> sqlWrapper) {
        return sqlHelper.queryList(sqlWrapper,sqlWrapper.SQL().toSqlStructure(), sqlWrapper.SQL().getParams().toArray());
    }
    public <T> Map<String, Object> queryMap(LambdaSQL<T> sqlWrapper) {
        return sqlHelper.queryMap(sqlWrapper,sqlWrapper.SQL().toSqlStructure(), sqlWrapper.SQL().getParams().toArray());
    }

    //批量执行
    @SafeVarargs
    public   final <T> int[] batchExecute(LambdaSQL<T>... sqlWrappers) {
        String[] sqls = new String[sqlWrappers.length];
        for (int i = 0; i < sqlWrappers.length; i++) {
            sqls[i] = sqlWrappers[i].SQL().toSqlStructure();
        }
        return sqlHelper.batchExecute(sqlWrappers,sqls);
    }
    public final <T> int[] batchExecute(List<LambdaSQL<T>> sqlWrappers) {
        String[] sqls = new String[sqlWrappers.size()];
        for (int i = 0; i < sqlWrappers.size(); i++) {
            sqls[i] = sqlWrappers.get(i).SQL().toSqlStructure();
        }
        return sqlHelper.batchExecute(sqlWrappers.toArray(new LambdaSQL[0]),sqls);
    }
    //增删改等操作都可以用这个
    public <T> int   execute(LambdaSQL<T> sqlWrapper) {
       return  sqlHelper.execute(sqlWrapper,sqlWrapper.SQL().toSqlStructure(), sqlWrapper.SQL().getParams().toArray());
    }


    //事物
    public <T> void transaction(Function<SqlWrapperHelper,Void> function) {
        sqlHelper.executeInTransaction((data) -> function.apply(this));

    }

}
